package com.easygo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.easygo.dao.GoodsDao;
import com.easygo.mapper.GoodsMapper;
import com.easygo.pojo.Goods;
import com.easygo.service.GoodsService;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;
import org.springframework.data.elasticsearch.core.query.SearchQuery;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

@Service
public class GoodsServiceImpl extends ServiceImpl<GoodsMapper,Goods> implements GoodsService {

    @Resource
    GoodsDao goodsDao;  //索引库

    @Resource
    GoodsMapper goodsMapper; //数据库

    @Override
    public Goods saveDocument(Goods goods) {
        return goodsDao.save(goods);
    }

    @Override
    public Goods updateDocumentById(Goods goods) {
        return goodsDao.save(goods);
    }

    @Override
    public void deleteDocument(Goods goods) {
        goodsDao.delete(goods);
    }

    @Override
    public Page<Goods> selectDocumentByPage(Integer pageIndex, Integer pageSize) {
        Pageable pageable = PageRequest.of(pageIndex,pageSize);
        Page<Goods> page = goodsDao.findAll(pageable);
        return page;
    }

    @Override
    public Page<Goods> pageQuery(Integer pageIndex, Integer pageSize, String keywords) {
        SearchQuery searchQuery=new NativeSearchQueryBuilder().withQuery(QueryBuilders.matchPhraseQuery("goodsName",keywords))
                .withPageable(PageRequest.of(pageIndex,pageSize)).build();
        return goodsDao.search(searchQuery);
    }

    @Override
    public List<Goods> getGoods() {
        return goodsMapper.selectList(new QueryWrapper<Goods>().eq("is_delete",0).eq("is_marketable",1));
    }

    @Override
    public List<Goods> findGoodsByGoodsName(String goodsName) {
        return goodsDao.findGoodsByGoodsName(goodsName);
    }

    @Override
    public Page<Goods> findGoodsByGoodsName(String condition, Pageable pageable) {
        return goodsDao.findGoodsByGoodsName(condition,pageable);
    }

    @Override
    public Page<Goods> findGoodsByGoodsNameOrCaption(String goodsName, String caption, Pageable pageable) {
        return goodsDao.findGoodsByGoodsNameOrCaption(goodsName,caption,pageable);
    }


}
